#!/bin/bash

# 获取操作系统类型
platform=$(uname)

# 定义 Chrome 路径
if [ "$platform" == "Darwin" ]; then
    # macOS
    CHROME_PATH="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
elif [ "$platform" == "Linux" ]; then
    # Linux
    CHROME_PATH="google-chrome"
else
    # Windows
    if [ -f "/c/Program Files/Google/Chrome/Application/chrome.exe" ]; then
        CHROME_PATH="/c/Program Files/Google/Chrome/Application/chrome.exe"
    elif [ -f "/c/Program Files (x86)/Google/Chrome/Application/chrome.exe" ]; then
        CHROME_PATH="/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"
    else
        echo "错误：未找到 Chrome 浏览器"
        exit 1
    fi
fi

# 检查 Chrome 是否已安装
if [ ! -f "$CHROME_PATH" ]; then
    echo "错误：Chrome 浏览器未安装或路径不正确"
    exit 1
fi

# 检查是否已经有 Chrome 实例在运行
if [ "$platform" == "Darwin" ]; then
    pgrep -f "Google Chrome" > /dev/null
    if [ $? -eq 0 ]; then
        echo "Chrome 已经在运行，先关闭它..."
        pkill -f "Google Chrome"
        sleep 2
    fi
elif [ "$platform" == "Linux" ]; then
    pgrep -f "google-chrome" > /dev/null
    if [ $? -eq 0 ]; then
        echo "Chrome 已经在运行，先关闭它..."
        pkill -f "google-chrome"
        sleep 2
    fi
else
    # Windows
    tasklist | findstr "chrome.exe" > /dev/null
    if [ $? -eq 0 ]; then
        echo "Chrome 已经在运行，先关闭它..."
        taskkill /F /IM chrome.exe /T
        sleep 2
    fi
fi

# 启动 Chrome 并打开指定页面
if [ "$platform" == "Windows" ]; then
    # Windows 下使用双引号包裹路径
    "$CHROME_PATH" --remote-debugging-port=9222 --remote-debugging-address=127.0.0.1 https://shangoue.meituan.com
else
    # 其他系统直接使用路径
    "$CHROME_PATH" --remote-debugging-port=9222 --remote-debugging-address=127.0.0.1 https://shangoue.meituan.com
fi

# 检查启动是否成功
if [ $? -ne 0 ]; then
    echo "错误：启动 Chrome 失败"
    exit 1
fi

echo "Chrome 已成功启动"